package com.github.tommas;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args )
    {
        ServiceInterface dpService = getDynamicProxyService();
        ServiceInterface scService = getServiceFromSpringContext();

        System.out.printf("Dynamic proxy service, foo = %s, bar = %s%n", dpService.foo(), dpService.bar());
        System.out.printf("Spring context proxy service, foo = %s, bar = %s%n", scService.foo(), scService.bar());
    }

    private static ServiceInterface getDynamicProxyService() {
        return (ServiceInterface) Proxy.newProxyInstance(
                ServiceInterface.class.getClassLoader(),
                new Class[]{ServiceInterface.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        String methodName = method.getName();
                        if ("foo".equals(methodName)) {
                            return "dp-foo";
                        } else if ("bar".equals(methodName)) {
                            return "dp-bar";
                        } else {
                            throw new RuntimeException("Unknown method: " + methodName);
                        }
                    }
                });
    }

    private static ServiceInterface getServiceFromSpringContext() {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(SpringConfigClass.class);
        return context.getBean(ServiceInterface.class);
    }
}
